import re
import os
import sys

# 定义正则表达式用于匹配 "messgame" 字段和数字
message_pattern = re.compile(r'message ')
number_pattern = re.compile(r'\d+$')
# 匹配protoId 的变量名
name_pattern = re.compile(r'\S+$')

#读取文件路径
read_file_name = sys.argv[1]
#写取文件路径
write_file_name = sys.argv[2]

# 读取文件并进行匹配
with open(read_file_name, "r") as file:
    proto_ids = []  # 存储匹配到的数字
    proto_id_names = []  # 存储匹配到的变量名
    for line in file:
        line.replace("\n", "") #去除换行符
        line.strip() #去除两边空格
        if message_pattern.search(line):  # 匹配 "message " 字段
            match = number_pattern.search(line)  # 从末尾开始匹配数字
            if match:
                proto_id = match.group()  # 获取匹配到的数字
                proto_ids.append(proto_id)
                name = name_pattern.search(line) # 获取匹配到的名字
                proto_id_names.append(name.group())

# 写入文件
with open(write_file_name, "w") as proto_file:
    proto_file.write("using System;\n")
    proto_file.write("\n")
    proto_file.write("public class ProtoId\n")
    proto_file.write("{\n")
    # 写入 protoId 
    for index, value in enumerate(proto_ids):
        name = proto_id_names[index]
        variableStr = "\tpublic const ushort {} = {};\n".format(name,value)
        proto_file.write(variableStr)
        
    # 写入根据type 获取对应的 protoId 方法
    proto_file.write("\n")
    proto_file.write("\tpublic static ushort Get(System.Type _Type)\n")
    proto_file.write("\t{\n")
    for index, value in enumerate(proto_ids):
        name = proto_id_names[index]
        judgeStr = "\t\tif(typeof(Message.{}) == _Type) return {};\n".format(name,value)
        proto_file.write(judgeStr)
    proto_file.write("\t\treturn 0;\n")
    proto_file.write("\t}\n")
    proto_file.write("}")
    
    